$(() => {
  let laypage = layui.laypage
  let form = layui.form
  let query = {
    pagenum: 1,
    pagesize: 3,
  }
  function getUser() {
    $.ajax({
      url: 'admin/users',
      data: query,
      success: (msg) => {
        if (msg.status === 0) {
          document.querySelector('tbody').innerHTML = template('userInfo', msg)
          renderPage(msg.total)
        } else {
          layer.msg('获取用户数据失败')
        }
      },
    })
  }
  //初始化数据
  getUser()

  //分页函数
  function renderPage(count) {
    laypage.render({
      elem: 'page',
      count,
      limit: query.pagesize,
      limits: [3, 10, 30, 40, 100],
      curr: query.pagenum,
      layout: ['prev', 'page', 'next', 'skip', 'count', 'limit'],
      jump: function (obj, first) {
        query.pagenum = obj.curr
        query.pagesize = obj.limit
        if (!first) {
          getUser()
        }
      },
    })
  }

  //删除用户
  $('body').on('click', '#delBtn', function () {
    let id = $(this).attr('data-id')
    $.ajax({
      url: 'admin/users/' + id,
      type: 'DELETE',
      success: (msg) => {
        if (msg.status === 0) {
          layer.msg(msg.message)
          getUser()
        } else {
          layer.msg(msg.message)
        }
      },
    })
  })

  //编辑用户
  $('body').on('click', '#editBtn', function () {
    let id = $(this).siblings('#delBtn').attr('data-id')
    sessionStorage.setItem('userId', id)
    location.href = './edit.html'
  })

  //重置密码
  $('body').on('click', '#resetPwd', function () {
    let id = $(this).siblings('#delBtn').attr('data-id')
    let index = layer.open({
      title: '重置密码',
      type: 1,
      content: $('#rePwd-tpl').html(),
      area: ['500px', '250px'],
    })
    sessionStorage.setItem('userId', id)
    sessionStorage.setItem('index', index)
    //重置密码功能
    $('#rePwd').on('submit', (e) => {
      let id = sessionStorage.getItem('userId')
      e.preventDefault()
      let data = form.val('rePwd')
      if (data.password !== data.rePwd) {
        layer.msg('两次输入密码不一致')
      } else {
        $.ajax({
          url: 'admin/users/' + id,
          type: 'PUT',
          data,
          success: (msg) => {
            if (msg.status === 0) {
              layer.msg(msg.message, { time: 1000 }, () => {})
              let index = sessionStorage.getItem('index')
              layer.close(index)
              sessionStorage.clear()
            } else {
              layer.msg(msg.message)
            }
          },
        })
      }
    })
  })
})
